use Getopt::Std;
#Input Arguments
getopt("t:q", \%args);
$infile = $args{t};
chomp($infile);
$QC = $args{q};
chomp($QC);
open TFAM,"$infile.tfam" or die "can't open $infile.tfam\n";
open QC,"$QC" or die "can't open $QC\n";
$outfile = "$infile".'_removeddup';
$outQC = $QC;
$outQC =~ s/\.tped//g;
$outQC = "$outQC".'_removeddup';
open(WRTFAM,">$outfile.tfam");
open(WRQC,">$outQC");
#QC header
$line = <QC>;
if($line !~ m/^SampleID/ )
{
	open QC,"$QC" or die "can't open $QC\n";
}
#opening QC file
$num = 0;
#parsin g the qc file
while($line = <QC>)
{
	chomp($line);
	@array = split(/\t/,$line);
	@array1 = split('-',$array[0]);
	if($array[1] eq "Y")
	{	#ctga first 4 columns
		$temp = $array1[0].'-'.$array1[1].'-'.$array1[2].'-'.$array1[3];
		$array[0] = $temp;
		$line = join("\t",@array);
		$value = $array[2]/$array[3];
		$line1 = <TFAM>;
		@tarray = ();
		@tarray = split(" ",$line1);
		@tarray1 = ();
		@tarray1 = split('-',$tarray[1]);
		
		$temp1 = $tarray1[0].'-'.$tarray1[1].'-'.$tarray1[2].'-'.$tarray1[3];		
		if($temp eq $temp1)
		{	if(!(exists($sample{$temp})))
			{
				$sample{$temp} = $num;
				$value{$temp} = $value;
				$sampleQC{$temp} = $line;
				$sampleIND{$temp} = $array[5];
				$tfamarray{$temp} = "$tarray[0] $temp $tarray[2] $tarray[3] $tarray[4] $tarray[5]";
				$all1 = 2*$num;
				$all2 = $all1+1;
				$tfamarraynum{$temp} = $all1." ".$all2;
			}
			else
			{
				if($array[5] > $sampleIND{$temp} || ($value < $value{$temp} && $sampleIND{$temp}<= $array[5]))
				{
					$sample{$temp} = $num;
					$value{$temp} = $value;
					$sampleIND{$temp} = $array[5];
					$sampleQC{$temp} = $line;
					$tfamarray{$temp} = "$tarray[0] $temp $tarray[2] $tarray[3] $tarray[4] $tarray[5]";
					$all1 = 2*$num;
					$all2 = $all1+1;
					$tfamarraynum{$temp} = $all1." ".$all2;
				}	
			}
			$num++;
		}
		else
		{
			die "sample QC sample ID $temp is not equal to tfam sample ID $temp1\n";
		}
	}
}
foreach $key (sort {$sample{$a} <=> $sample{$b} } keys %sample)
{
	@array = ();
     	@array = split(" ",$tfamarraynum{$key});
     	print WRTFAM $tfamarray{$key}."\n";
     	print WRQC $sampleQC{$key}."\n"; 
}

